﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kooboo.HtmlFunc;
using Kooboo.CMS.SiteConverter.Models;

namespace Kooboo.CMS.SiteConverter.Parser.Razor
{
    public class FileUrlParser : ParserBase, IParser<FileUrl>
    {
        public const string FilesFolderName = "Files/";
        public const string StylesFolderName = "Styles/";
        public const string ScriptsFolderName = "Scripts/";

        public static void FillResult(ParserContext context, FileUrl obj, string formater)
        {
            switch (obj.Node.Name.ToLower())
            {
                case "script":
                    var scriptSrc = obj.Node.Attr("src") ?? string.Empty;
                    if (scriptSrc.IgnoreCaseStartsWith(ScriptsFolderName))
                    {
                        context.Result.OrderedScripts.Add(scriptSrc);
                        obj.Node.RemoveWithPrevWhitespace();
                    }
                    break;

                case "link":
                    var linkHref = obj.Node.Attr("href") ?? string.Empty;
                    if (linkHref.IgnoreCaseStartsWith(StylesFolderName))
                    {
                        context.Result.OrderedStyles.Add(linkHref);
                        obj.Node.RemoveWithPrevWhitespace();
                    }
                    break;

                case "img":
                    var imgSrc = obj.Node.Attr("src") ?? string.Empty;
                    if (imgSrc.IgnoreCaseStartsWith(FilesFolderName))
                    {
                        var fileUrl = imgSrc.Substring(FilesFolderName.Length);
                        obj.Node.Attr("src", string.Format(formater, fileUrl));
                    }
                    break;

                case "a":
                    var anchorHref = obj.Node.Attr("href") ?? string.Empty;
                    if (anchorHref.IgnoreCaseStartsWith(FilesFolderName))
                    {
                        var fileUrl = anchorHref.Substring(FilesFolderName.Length);
                        obj.Node.Attr("href", string.Format(formater, fileUrl));
                    }
                    break;

                default:
                    break;
            }
        }

        #region IParser<FileUrl> Members

        public void Parse(FileUrl obj)
        {
            var format = "@Url.FrontUrl().FileUrl(\"{0}\")";
            FillResult(this.Context, obj, format);
        }

        #endregion
    }
}
